package com.khson.knows.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.khson.knows.portal.mapper.QuestionMapper;
import com.khson.knows.portal.mapper.UserMapper;
import com.khson.knows.portal.model.Question;
import com.khson.knows.portal.model.Tag;
import com.khson.knows.portal.model.User;
import com.khson.knows.portal.service.IQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author com.khson
 * @since 2021-08-23
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public PageInfo<Question> getMyQuestions(String username,Integer pageNum,Integer pageSize) {
        //1,根据用户名(手机号)查询用户信息
        User user = userMapper.findUserByUsername(username);
        //2,根据用户信息查询问题
        QueryWrapper<Question> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",user.getId());
        wrapper.eq("delete_status",0);
        //设置时间降序排序
        //3.执行查询
        //startPage方法的参数我们写两个,第一个是要查询第几页,如果想查询第一页就写1
        //第二个参数时当前页最多显示多少
        PageHelper.startPage(pageNum,pageSize);
        wrapper.orderByDesc("createtime");
        List<Question> questions = questionMapper.selectList(wrapper);
        for (Question question:questions) {
            question.setTags(tagNames2Tags(question.getTagNames()));
//            questions.add(question);  //遍历到的 question就是 List<Question>列表中的对象,对其操作就是对List<Question>列表,中的对象进行操作
        }
        return new PageInfo<>(questions);
    }

    @Autowired
    private TagServiceImpl tagService;
    //根据当前Question的tagName属性,获取对应的List<Tag>集合
    private List<Tag> tagNames2Tags(String tagNames){
        List<Tag> tags = new ArrayList<>();
        String[] names = tagNames.split(",");
        Map<String, Tag> tagMap = tagService.getTagMap();
        for (String name:names) {
            tags.add(tagMap.get(name));
        }
        return tags;
    }
}
